package si.cir.gui;

import java.util.ArrayList;
import java.util.List;

import si.cir.R;
import si.cir.entities.IzpitniRok;
import si.cir.util.WSclient;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AipsListFragment extends ListFragment {
	
	private List<IzpitniRok> izpitniRoki;
	private String predmetId;
	
	private Runnable getNoviceBackgroundThread = new Runnable() {
		public void run() {
			getRokiInBackgroundThread();
		}
	};
	
	public AipsListFragment(String predmetId){
		this.predmetId = predmetId;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(false);

		Thread thread = new Thread(null, getNoviceBackgroundThread, "Background");
		thread.start();
	}
	
	private void getRokiInBackgroundThread() {
		izpitniRoki = WSclient.getIzpitniRoki(predmetId);
		if(izpitniRoki != null && izpitniRoki.size() != 0){
			final List<String> naslovi = new ArrayList<String>();
			for(IzpitniRok ir : izpitniRoki)
				naslovi.add(ir.getDatum() + (ir.getUra() != null ? " ob " + ir.getUra() : ""));
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.simple_item, naslovi));
					setListShown(true);
				}
			});
		}else{
			getActivity().runOnUiThread(new Runnable() {

				public void run() {
					Toast.makeText(getActivity(), "V tej kategoriji ni objav",
						Toast.LENGTH_LONG).show();
					getActivity().finish();
				}
			});
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(izpitniRoki.get(position).getProstor() + "\n\nTip: " + 
				izpitniRoki.get(position).getTip() + "\nKomisijski: " + izpitniRoki.get(position).getKomisijski()
				+ ((izpitniRoki.get(position).getOpomba() == null) ? "" : "\n\n* " + izpitniRoki.get(position).getOpomba()))
		       .setCancelable(true);
		AlertDialog alert = builder.create();
		alert.show();
	}
}
